package org.suburban.servlet;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.SendResponse.Status;

/**
 * Servlet to send invitation to the client
 * @author Alexey Palamarchuk (slonnik@gmail.com)
 *
 */
@SuppressWarnings("serial")
public class ClientInvitationServlet  extends ClientServlet {
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		/** call super class method*/
		super.doPost(req, resp);
		
		/** let's update vCard with the schedule name*/
		updateVCard();
		/** send invitation*/
		xmpp.sendInvitation(originator, client);
	}
	/**
	 * Update client vCard with the human readable schedule name
	 */
	private void updateVCard()
	{
		String stanza = "<iq id=\"v2\" type=\"set\">" + 
							"<vCard xmlns=\"vcard-temp\">" + 
								"<NICKNAME>%1$s</NICKNAME>" +
							"</vCard>" +
						"</iq>";
		
		Message xmppMessage = new MessageBuilder()
								.asXml(true)
								.withFromJid(client)
								.withRecipientJids(originator)
								.withBody(String.format(stanza, scheduleName))
								.build();

		SendResponse response = xmpp.sendMessage(xmppMessage);
	
		/** trace vCard update respond*/
		if(logger.isLoggable(Level.FINE) == true)
		{
			Map<JID, Status> data = response.getStatusMap();
			if(data.containsKey(client) == true)
			{
				logger.log(Level.FINE, "Update vCard status={0}", data.get(client).toString());
			}
			else
			{
				logger.log(Level.FINE, "No responce for vCard update");
			}
		}
		
	}
}
